package tech.bmatch.meituan.service.impl;

import tech.bmatch.meituan.model.Merchant;
import tech.bmatch.meituan.model.MerchantSearchParam;
import tech.bmatch.meituan.util.DistanceUtil;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MerchantServiceImpl extends MerchantFileStoreServiceImpl {

    private Map<String, Merchant> merchants;

    public void add(Merchant merchant) {
        if (merchants == null) {
            merchants = new HashMap<String, Merchant>();
        }
        if (merchant == null) {
            return;
        }

        merchants.put(merchant.getId(), merchant);

        Set<Merchant> merchantList = merchants.values().stream().collect(Collectors.toSet());

        store(merchantList);
    }


    public Set<Merchant> search(MerchantSearchParam param) {

        Set<Merchant> merchantList = new HashSet<Merchant>();
        for (Map.Entry<String, Merchant> merchantEntry : merchants.entrySet()) {
            Merchant merchant = merchantEntry.getValue();
            Double distance = DistanceUtil.getDistance(param.getLon(), param.getLat(), merchant.getLon(), merchant.getLat());
            merchant.setDistance(distance);
            merchantList.add(merchantEntry.getValue());
        }

        Stream<Merchant> stream = merchantList.stream();

        if (param.getName() != null && !param.getName().equals("")) {
            stream = stream.filter(m -> m.getName().indexOf(param.getName()) >= 0);
        }
        stream = stream.sorted((m1, m2) -> ((Double) m1.getDistance()).intValue() - ((Double) m2.getDistance()).intValue());

        return stream.collect(Collectors.toSet());
    }


}
